#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using TVC.Layout;
using System.Xml;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;
using QueryBuilder;
using TVC.Report;
using FlexCel.Core;
using Gizmox.WebGUI.Common.Gateways;

#endregion

namespace TVC.Modules.Act
{
    public partial class ICAT : ModuleParent, IHostedApplication
    {

        int idAllowEditLanguage = 1;
        int idAddNew = 238;
        int idEdit = 239;
        int idDelete = 240;
        int idPrint = 241;
        int idTransferOut = 242;
        int idToExcel = 253;

        public ICAT()
        {
            InitializeComponent();

            _strType = "ICAT";
            _tvList = tvCategory;
            _dgvFilter = gridFilter1;
            gridFilter1.GridFiterEvent += new CustomControl.GridFilter.GridFilterHandle(_dgvFilter_GridFiterEvent);

        }

        void cbMainCode_SelectedValueChanged(object sender, EventArgs e)
        {
            cbMainName.SelectedValue = cbMainCode.SelectedValue;
            cbMainCode.Focus();
        }

        void _dgvFilter_GridFiterEvent(string strFilter, int year)
        {
            string sErr = "";
            BUS.TVC_CATEControl MMQCtr = new BUS.TVC_CATEControl();
            DataTable dtb = null;
            dtb = MMQCtr.GetbyFilter(GetMainForm().PODInfo.Business_ID, strFilter, ref sErr);
            if (!string.IsNullOrEmpty(gridFilter1.SortField))
            {
                dtb.DefaultView.Sort = gridFilter1.SortField + " " + gridFilter1.Direction;
            }
            LoadTreeView(dtb);
        }

        private void LoadTreeView(DataTable dtb)
        {
            //  DataTable dtFilter = gridFilter1.GetData();

            var tmp = dtb.AsEnumerable();

            //Filter

            var dt = tmp.GroupBy(r => new { maingroup = r["maingroup"], mainname = r["mainname"] })
                  .Select(g => new { maingroup = g.Key.maingroup, mainname = g.Key.mainname }).ToList();


            tvCategory.Nodes.Clear();

            foreach (var xMain in dt)
            {
                TreeNode nMain = tvCategory.Nodes.Add(string.Format("{0} - {1}", xMain.maingroup.ToString(), xMain.mainname.ToString()));
                nMain.NodeFont = new Font(this.Font, FontStyle.Bold);

                DTO.TVC_CATE2Info infMain = new DTO.TVC_CATE2Info(xMain.maingroup.ToString(), xMain.mainname.ToString());
                nMain.Tag = infMain;

                var dtSub = dtb.AsEnumerable()
                    .Where(r => r.Field<string>("maingroup") == (string)xMain.maingroup)
                    .Where(r => r.Field<string>("subgroup") != "")
                    .Select(r => new { maingroup = r["maingroup"], subgroup = r["subgroup"], subname = r["subname"] })
                    .GroupBy(g => new { g.maingroup, g.subgroup, g.subname })
                    .OrderBy(g => g.Key.subgroup)
                    //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                    .ToList();

                var dtSize = dtb.AsEnumerable()
                    .Where(r => r.Field<string>("maingroup") == (string)xMain.maingroup)
                    .Where(r => r.Field<string>("sizecode") != "")
                    .Select(r => new { maingroup = r["maingroup"], sizecode = r["sizecode"], sizename = r["sizename"] })
                    .GroupBy(g => new { g.maingroup, g.sizecode, g.sizename })
                    .OrderBy(g => g.Key.sizecode)
                    //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                    .ToList();

                var dtLen = dtb.AsEnumerable()
                    .Where(r => r.Field<string>("maingroup") == (string)xMain.maingroup)
                    .Where(r => r.Field<string>("lengthcode") != "")
                    .Select(r => new { maingroup = r["maingroup"], lengthcode = r["lengthcode"], lengthname = r["lengthname"] })
                    .GroupBy(g => new { g.maingroup, g.lengthcode, g.lengthname })
                    .OrderBy(g => g.Key.lengthcode)
                    //  .Where(g => g.Key.maingroup == dt[i].maingroup)
                    .ToList();

                foreach (var subRow in dtSub)
                {
                    if ((string)subRow.Key.subgroup != "")
                    {
                        TreeNode nSub = nMain.Nodes.Add(string.Format("{0} - {1}", subRow.Key.subgroup, subRow.Key.subname));
                        DTO.TVC_CATE1Info infSub = new DTO.TVC_CATE1Info((string)xMain.maingroup, "1", (string)subRow.Key.subgroup, (string)subRow.Key.subname);
                        nSub.Tag = infSub;
                        foreach (var sizeRow in dtSize)
                        {
                            if ((string)sizeRow.Key.sizecode != "")
                            {
                                TreeNode nSize = nSub.Nodes.Add(string.Format("{0} - {1}", sizeRow.Key.sizecode, sizeRow.Key.sizename));
                                DTO.TVC_CATE1Info infSize = new DTO.TVC_CATE1Info((string)sizeRow.Key.maingroup, "2", (string)sizeRow.Key.sizecode, (string)sizeRow.Key.sizename);
                                nSize.Tag = infSize;
                                foreach (var lenRow in dtLen)
                                {
                                    TreeNode nLen = nSize.Nodes.Add(string.Format("{0} - {1}", lenRow.Key.lengthcode, lenRow.Key.lengthname));
                                    if ((string)lenRow.Key.lengthcode != "")
                                    {
                                        nLen.Tag = new DTO.TVC_CATE1Info((string)lenRow.Key.maingroup, "3", (string)lenRow.Key.lengthcode, (string)lenRow.Key.lengthname);
                                    }
                                }
                            }

                        }
                    }

                }
            }
        }

        #region .::| Override Functions |::.

        protected override bool checkExists()
        {
            if (cbType.SelectedValue + "" != "")
            {
                BUS.TVC_CATE1Control ctr = new BUS.TVC_CATE1Control();
                return ctr.IsExist(GetMainForm().PODInfo.Business_ID, cbMainCode.Text, cbType.SelectedValue + "", txCode.Text);
            }

            BUS.TVC_CATE2Control ctrP = new BUS.TVC_CATE2Control();
            return ctrP.IsExist(GetMainForm().PODInfo.Business_ID, cbMainCode.Text);

        }

        protected override ErrorStatus validateForm(ref string sErr)
        {
            ErrorStatus res = ErrorStatus.SUCCESS;
            if (cbMainCode.Text == "")
            {
                sErr = "Main Code DO NOT blank! please check";
                res = ErrorStatus.ERROR;
            }
            return res;
        }
        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.TVC_CATE1Control ctr = new BUS.TVC_CATE1Control();
            BUS.TVC_CATE2Control ctrParent = new BUS.TVC_CATE2Control();

            DTO.TVC_CATE1Info info = GetData();
            string db = GetMainForm().PODInfo.Business_ID;
            info.db = db;
            object trans = ctr.BeginTransaction(ref sErr);

            if (!ctrParent.IsExist(db, cbMainCode.SelectedValue + ""))
            {
                ctrParent.SetTransaction(trans);
                ctrParent.Add(new DTO.TVC_CATE2Info(cbMainCode.Text, cbMainName.Text) { db = info.db }, ref sErr);
            }
            //ctrDet.SetTransaction(trans);

            //if (sErr == "") sErr = SaveMaterialDetail(info.db, ctrDet);

            if (sErr == "" && info.typevalue != "") ctr.Add(info, ref sErr);

            if (sErr == "")
            {
                BUS.TVC_CATEControl ctrDetail = new BUS.TVC_CATEControl();
                ctrDetail.SetTransaction(trans);
                sErr = ctrDetail.Delete(db, cbMainCode.Text);

                if (sErr == "")
                {
                    DataTable dt = ctrDetail.GetCateFrom12(db, cbMainCode.Text, ref sErr);

                    foreach (DataRow r in dt.Rows)
                    {
                        if (sErr == "")
                        {
                            ctrDetail.Add(new DTO.TVC_CATEInfo(r) { db = db, rowrank = string.Format("{0:0000}", dt.Rows.IndexOf(r)) }, ref sErr);
                        }
                    }
                }
            }
            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);

            return sErr;
        }


        protected override string updateRecord(bool isDraft = false)
        {
            string sErr = "";
            BUS.TVC_CATE1Control ctr = new BUS.TVC_CATE1Control();
            BUS.TVC_CATE2Control ctrParent = new BUS.TVC_CATE2Control();

            DTO.TVC_CATE2Info infParent = ctrParent.Get(GetMainForm().DB, cbMainCode.Text, ref sErr);

            DTO.TVC_CATE1Info info = GetData();
            string db = info.db = GetMainForm().PODInfo.Business_ID;

            object trans = ctr.BeginTransaction(ref sErr);

            if (infParent.mainname != cbMainName.Text)
            {
                ctrParent.SetTransaction(trans);
                sErr = ctrParent.Update(new DTO.TVC_CATE2Info(cbMainCode.Text, cbMainName.Text) { db = info.db });
            }

            //    ctrDet.SetTransaction(trans);

            //  if (sErr == "") sErr = SaveMaterialDetail(info.db, ctrDet);

            if (sErr == "") sErr = ctr.Update(info);
            if (sErr == "")
            {
                BUS.TVC_CATEControl ctrDetail = new BUS.TVC_CATEControl();
                ctrDetail.SetTransaction(trans);
                sErr = ctrDetail.Delete(db, cbMainCode.Text);

                if (sErr == "")
                {
                    DataTable dt = ctrDetail.GetCateFrom12(db, cbMainCode.Text, ref sErr);

                    foreach (DataRow r in dt.Rows)
                    {
                        if (sErr == "")
                        {
                            ctrDetail.Add(new DTO.TVC_CATEInfo(r) { db = db, rowrank = string.Format("{0:0000}", dt.Rows.IndexOf(r)) }, ref sErr);
                        }
                    }
                }
            }

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }
        protected override string delRecord()
        {
            string sErr = "";
            BUS.TVC_CATE1Control ctr = new BUS.TVC_CATE1Control();
            BUS.TVC_CATE2Control ctrParent = new BUS.TVC_CATE2Control();
            string db = GetMainForm().PODInfo.Business_ID;
            object trans = ctr.BeginTransaction(ref sErr);

            if (cbType.SelectedValue + "" == "")
            {
                if (sErr == "") sErr = ctrParent.Delete(db, cbMainCode.Text);
                if (sErr == "") sErr = ctr.Delete(db, cbMainCode.Text);
            }
            else
            {
                if (sErr == "") sErr = ctr.Delete(db, cbMainCode.Text, cbType.SelectedValue + "", txCode.Text);
            }
            // if (sErr == "") sErr = ctrDet.Delete(GetMainForm().PODInfo.Business_ID == "HL" ? Properties.Settings.Default.SUNHL : Properties.Settings.Default.SUNHV, txRequestNo.Text);
            if (sErr == "")
            {
                BUS.TVC_CATEControl ctrDetail = new BUS.TVC_CATEControl();
                ctrDetail.SetTransaction(trans);
                sErr = ctrDetail.Delete(db, cbMainCode.Text);

                if (sErr == "")
                {
                    DataTable dt = ctrDetail.GetCateFrom12(db, cbMainCode.Text, ref sErr);

                    foreach (DataRow r in dt.Rows)
                    {
                        if (sErr == "")
                        {
                            ctrDetail.Add(new DTO.TVC_CATEInfo(r) { db = db, rowrank = string.Format("{0:0000}", dt.Rows.IndexOf(r)) }, ref sErr);
                        }
                    }
                }
            }

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }



        protected override void refreshForm(string str)
        {
            cbMainCode.Text = str;
            cbMainName.Text = str;
            cbType.Text = str;
            txCode.Text = str;
            txName.Text = str;
        }
        protected override void enableForm(bool val)
        {
            cbMainCode.Enabled = val;
            cbMainName.Enabled = val;
            cbType.Enabled = val;
            txCode.Enabled = val;
            txName.Enabled = val;

        }
        protected override void loadRecord(object o)
        {
            if (o is TreeNode)
            {
                TreeNode node = o as TreeNode;
                DTO.TVC_CATE1Info inf = node.Tag as DTO.TVC_CATE1Info;
                if (inf != null)
                {
                    SetData(inf);
                }
                else
                {
                    DTO.TVC_CATE2Info inf1 = node.Tag as DTO.TVC_CATE2Info;
                    if (inf1 != null)
                    {
                        inf = new DTO.TVC_CATE1Info()
                        {
                            maingroup = inf1.maingroup,
                            subtype = "0"
                        };
                        SetData(inf);
                    }
                }
            }
        }

        private void SetData(DTO.TVC_CATE1Info inf)
        {
            cbMainCode.Text = inf.maingroup;
            cbType.SelectedValue = inf.subtype;
            txCode.Text = inf.typevalue;
            txName.Text = inf.typename;
        }

        #endregion
        private DTO.TVC_CATE1Info GetData()
        {
            DTO.TVC_CATE1Info inf = new DTO.TVC_CATE1Info()
            {
                maingroup = cbMainCode.Text,
                subtype = cbType.SelectedValue + "",
                typevalue = txCode.Text,
                typename = txName.Text,
                db = GetMainForm().PODInfo.Business_ID
            };

            return inf;
        }

        public void InitializeApplication()
        {
        }

        public void SetObject(object obj)
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idAddNew) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S", false));
            if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Copy", "Copy", new IconResourceHandle("Copy.png"), "O"));
            objElements.Add(new HostedToolBarSeperator());
            if (IsPermis(idPrint)) objElements.Add(new HostedToolBarButton("Report", "Report", new IconResourceHandle("Print.png"), "P"));
            if (IsPermis(idToExcel)) objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Excel.png"), "E"));

            objElements.Add(new HostedToolBarButton("Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            sErr = "";
            string strAction = (string)objButton.Tag;

            BUS.ContractControl ctr = new BUS.ContractControl();
            switch (strAction)
            {
                case "C":
                    AddNew(cbMainCode);
                    break;
                case "A":
                    editRecord(cbMainCode);
                    cbType.Enabled = false;
                    txCode.Enabled = false;
                    break;
                case "S":
                    saveRecord(cbMainCode);
                    break;
                case "O":
                    copy(cbMainCode);
                    break;
                case "P":
                    // export2Excel();
                    {

                        SQLBuilder _sql = SQLBuilder.LoadSQLBuilderFromDataBase("ItemCate01_" + GetMainForm().PODInfo.Business_ID, "TVC", "");

                        //_sql.Filters[0].ValueFrom = "ZZZ";
                        //_sql.Filters[0].FilterFrom = "ZZZ";
                        //_sql.Filters[0].ValueTo = "";

                        ReportGenerator.User2007 = false;
                        ReportGenerator _report = new ReportGenerator(_sql, "ItemCate01_" + GetMainForm().PODInfo.Business_ID, "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        _report.UserID = GetMainForm().PODInfo.USER_ID;
                        ExcelFile exfile = _report.CreateReport();
                        ExcelFile file = exfile;
                        MemoryStream ms = new MemoryStream();
                        file.Save(ms);

                        DownloadGateway myDownload = new DownloadGateway(ms, "Item Category Tree - " + GetMainForm().PODInfo.Business_ID + ".xls");

                        myDownload.ContentType = "application/vnd.ms-excel";
                        myDownload.StartDownload(this);

                    }
                    break;
                case "E":
                    export2Excel();
                    break;
                case "K":
                    skip();
                    break;
                case "X":
                    delete(cbMainCode);
                    break;

                case "R":
                    reloadList();
                    break;

            }
            if (sErr == "")
                ThrowMsg("Command: " + _processStatus);
        }

        private void MMAT_Load(object sender, EventArgs e)
        {
            refreshForm("");
            enableForm(false);
            LoadComboBox();
            //gridFilter1.LoadData(GetMainForm().PODInfo.USER_ID,  "MMAT","MaterialReq", GetMainForm().PODInfo.Business_ID);
            //gridFilter1.panYear.Visible = false;
            //gridFilter1.btnOK_Click(sender, e);
        }

        private void LoadComboBox()
        {
            BUS.TVC_CATE2Control ctr = new BUS.TVC_CATE2Control();
            string db = GetMainForm().PODInfo.Business_ID;

            DataTable dt = ctr.GetAll(db, ref sErr);

            cbMainCode.DataSource = dt;
            cbMainCode.DisplayMember = "maingroup";
            cbMainCode.ValueMember = "maingroup";

            cbMainName.DataSource = dt.Copy();
            cbMainName.DisplayMember = "mainname";
            cbMainName.ValueMember = "maingroup";

            DataTable dtType = new DataTable();
            dtType.Columns.AddRange(new DataColumn[] { new DataColumn("id"), new DataColumn("text") });
            dtType.Rows.Add("1", "Sub Group");
            dtType.Rows.Add("2", "Size Group");
            dtType.Rows.Add("3", "Length Group");

            cbType.DataSource = dtType;
            cbType.DisplayMember = "text";
            cbType.ValueMember = "id";


        }

    }
}